<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车牌号" prop="licensePlate">
        <el-input
          v-model="queryParams.licensePlate"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车辆品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入车辆品牌"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车辆型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入车辆型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="购买日期" prop="purchaseDate">
        <el-date-picker clearable
          v-model="queryParams.purchaseDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择购买日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lh:carinfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lh:carinfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lh:carinfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['lh:carinfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="carinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车辆编号" align="center" prop="carId" />

        <el-table-column label="车辆照片" align="center" prop="photoUrl">  
        <template slot-scope="scope">  
          <img :src="scope.row.photoUrl"
           alt="车辆照片" 
          style="width: 120px; height: 80px; cursor:pointer;" 
          @click="handleImageClick(scope.row.photoUrl)" >  
        </template>  
      </el-table-column> 


      <el-table-column label="车牌号" align="center" prop="licensePlate" />
      <el-table-column label="车辆品牌" align="center" prop="brand" />
      <el-table-column label="车辆型号" align="center" prop="model" />
      <el-table-column label="购买日期" align="center" prop="purchaseDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车辆状态(1可用，0维修中，2报废)" align="center" prop="status" v-if="false"/>

     <el-table-column prop="status" label="车辆状态">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_carinfo_status" :value="scope.row.status"/>
        </template>
      </el-table-column>



      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['lh:carinfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lh:carinfo:remove']"
          >删除</el-button>

  <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownImage(scope.row.photoUrl)"
            v-hasPermi="['lh:carinfo:down']"
          >下载图片</el-button>



        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  <el-dialog
  :visible.sync="imageViewerVisible"
  width="50%"
  title="图片预览"
  @close="handleImageClose"
   >
  <img :src="currentImageUrl" alt="车辆照片" style="width: 100%;" />
    </el-dialog>

    <!-- 添加或修改车辆信息管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
       
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="form.licensePlate" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="车辆品牌" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入车辆品牌" />
        </el-form-item>
        <el-form-item label="车辆型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入车辆型号" />
        </el-form-item>
        <el-form-item label="购买日期" prop="purchaseDate">
          <el-date-picker clearable
            v-model="form.purchaseDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择购买日期">
          </el-date-picker>
        </el-form-item>





        <el-form-item label="图片地址" prop="photoUrl" v-if='false'>
          <el-input v-model="form.photoUrl" placeholder="输入图片地址"/>
        </el-form-item>

        <el-form-item label="图片" >
          <el-image
          style="width: 150px; height: 150px"
            :src="url"
            :fit="fit" ref="imageId" >
          </el-image>
                                         
          <el-button type="primary" @click="submitFileFormImage">上传图片</el-button>

          <el-upload
          ref="uploadFile"
          :limit="1"
          accept=".bmp,.jpg,.jpeg,.png,gif"
          :headers="uploadData.headers"
          :action="uploadData.url"
          :disabled="uploadData.isUploading"
          :on-progress="handleFileUploadDataProgress"
          :on-success="handleFileDataSuccess"
          :auto-upload="false"
          drag
          >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <span>仅允许导入bmp、jpg、jpeg、gif、png格式文件。</span>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCarinfo, getCarinfo, delCarinfo, addCarinfo, updateCarinfo } from "@/api/lh/carinfo";
import { getToken } from "@/utils/auth";


export default {
  name: "Carinfo",
  dicts: ['sys_carinfo_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车辆信息管理表格数据
      carinfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

       // 图片导入参数
      uploadData: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/lh/carinfo/uploadMinio"

      },
 imageViewerVisible: false,
      currentImageUrl: '',

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        photoUrl: null,
        licensePlate: null,
        brand: null,
        model: null,
        purchaseDate: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 初始图片URL 
      url:'',
      // 图片适应方式，这里设置为'contain' 
      fit:'contain'
    };
  },



  created() {
    this.getList();
  },
  methods: {
    /** 查询车辆信息管理列表 */
    getList() {
      this.loading = true;
      listCarinfo(this.queryParams).then(response => {
        this.carinfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        carId: null,
        photoUrl: null,
        licensePlate: null,
        brand: null,
        model: null,
        purchaseDate: null,
        status: null
      };
      this.resetForm("form");
      this.url="";
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.carId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车辆信息管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const carId = row.carId || this.ids
      getCarinfo(carId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改车辆信息管理";
        
        this.url = this.form.photoUrl;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.carId != null) {
            updateCarinfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCarinfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const carIds = row.carId || this.ids;
      this.$modal.confirm('是否确认删除车辆信息管理编号为"' + carIds + '"的数据项？').then(function() {
        return delCarinfo(carIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('lh/carinfo/export', {
        ...this.queryParams
      }, `carinfo_${new Date().getTime()}.xlsx`)
    },

 // 文件上传中处理
    handleFileUploadDataProgress(event, file, fileList) {
      console.log(getToken());
      console.log(event);
      console.log(file+"333");
      console.log(fileList+"333");
      this.uploadData.isUploading = true;
    },
    // 文件上传成功处理
    handleFileDataSuccess(response, file, fileList) {
       console.log(response);
       console.log(response.msg);
       console.log(file+"444");
       console.log(fileList+"555");
      this.uploadData.open = false;
      this.uploadData.isUploading = false;
      this.$refs.uploadFile.clearFiles();

      this.form.photoUrl = response.msg;

      this.url = this.form.photoUrl;

      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "上传图片成功！" + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    },
    // 提交上传文件
    submitFileFormImage() {
      this.$refs.uploadFile.submit();
    },

    //下载文件
    handleDownImage(filename){    
     let pos=filename.lastIndexOf("/");
     filename=filename.substring(pos);
     let extendName=filename.substring(filename.indexOf("."))  
     this.download('lh/carinfo/imageDown', {fileName:filename
      }, `carinfo_image_${new Date().getTime()}`+extendName)

    },


    handleCarinfoSubmit(carId){
        submitCarinfo(carId).then(response => {
          console.log(response)
          this.getList();
          this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "提交申请成功！" + "</div>", "提示框", { dangerouslyUseHTMLString: true });
       });
   },
    handleImageClick(photoUrl) {
      this.currentImageUrl = photoUrl;
      this.imageViewerVisible = true;
    },
    handleImageClose() {
      this.currentImageUrl = '';
      this.imageViewerVisible = false;
    }
    
 
  }
};
</script>
